using QFramework;
using UnityEngine;
using UnityEngine.UI;

namespace CounterApp
{
    public class CounterViewController : MonoBehaviour, IController
    {
        private ICounterModel _counterModel;

        private void Start()
        {
            // 获取
            _counterModel = this.GetModel<ICounterModel>();

            // 注册
            _counterModel.Count.Register(OnCountChanged);

            transform.Find("BtnAdd").GetComponent<Button>().onClick.AddListener(() =>
            {
                // 交互逻辑
                this.SendCommand<AddCountCommand>();
            });

            transform.Find("BtnSub").GetComponent<Button>().onClick.AddListener(() =>
            {
                // 交互逻辑
                this.SendCommand<SubCountCommand>();
            });

            OnCountChanged(_counterModel.Count.Value);
        }

        private void OnDestroy()
        {
            // 注销
            _counterModel.Count.UnRegister(OnCountChanged);

            _counterModel = null;
        }

        IArchitecture IBelongToArchitecture.GetArchitecture()
        {
            return CounterApp.Interface;
        }

        // 表现逻辑
        private void OnCountChanged(int newValue)
        {
            transform.Find("CountText").GetComponent<Text>().text = newValue.ToString();
        }
    }

    public interface ICounterModel : IModel
    {
        public BindableProperty<int> Count { get; }
    }

    /// <summary>
    ///     不需要是单例了
    /// </summary>
    public class CounterModel : AbstractModel, ICounterModel
    {
        public BindableProperty<int> Count { get; } = new()
        {
            Value = 0
        };

        protected override void OnInit()
        {
            // 通过 Architecture 获取
            var storage = this.GetUtility<IStorage>();

            Count.Value = storage.LoadInt("COUNTER_COUNT");

            Count.Register(count => storage.SaveInt("COUNTER_COUNT", count));
        }
    }
}